package cn.akira.domain.strategy.service.rule.tree.impl;

import cn.akira.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import cn.akira.domain.strategy.model.vo.StrategyAwardStockKeyVO;
import cn.akira.domain.strategy.repository.IStrategyRepository;
import cn.akira.domain.strategy.service.armory.IStrategyDispatch;
import cn.akira.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.akira.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author fjl95
 * @date 2025/5/16
 * @description 库存校验节点
 */
@Slf4j
@Component("rule_stock")
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Resource
    private IStrategyRepository strategyRepository;


    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date endDateTime) {
        log.info("规则过滤-库存扣减 userId:{},strategyId:{},awardId:{}", userId, strategyId, awardId);
        //扣减库存
        Boolean status = strategyDispatch.subtractionAwardStock(strategyId,awardId,endDateTime);
        //status true扣减成功 false扣减失败
        if (status) {
            //若扣减成功，写入延迟队列，会另外编写定时任务处理延迟队列
            strategyRepository.awardStockConsumeSendQueue(StrategyAwardStockKeyVO.builder()
                    .strategyId(strategyId)
                    .awardId(awardId)
                    .build());
            //返回状态设置为ALLOW
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVO(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .awardRuleValue("")
                            .build())
                    .build();
        }
        //返回状态设置为TAKE_OVER
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .build();
    }
}
